/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.tonyodev.fetchapp.ability;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.utils.Color;

import com.tonyodev.fetch2.Fetch;
import com.tonyodev.fetch2.FetchConfiguration;
import com.tonyodev.fetch2.Request;
import com.tonyodev.fetchapp.Data;
import com.tonyodev.fetchapp.ResourceTable;
import com.tonyodev.fetchapp.snackbar.SnackBar;

import java.util.ArrayList;
import java.util.List;

/**
 * @since 2021-05-20
 */
public class FailedMultiEnqueueAbility extends Ability {

    final static String FETCH_NAMESPACE = "FailedEnqueue";
    private Fetch fetch;
    private Component mainView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        getWindow().setStatusBarColor(Color.getIntColor("#303f9f"));
        super.setUIContent(ResourceTable.Layout_ability_multi_enqueue);
        mainView = findComponentById(ResourceTable.Id_ability_main);
        final FetchConfiguration fetchConfiguration = new FetchConfiguration.Builder(this)
            .setNamespace(FETCH_NAMESPACE)
            .build();
        fetch = Fetch.Impl.getInstance(fetchConfiguration)
            .deleteAll();

        final List<Request> requests = new ArrayList<>();
        final int size = 15;
        for (int x = 0; x < size; x++) {
            final String file = Data.getSaveDir(this) + "/multiTest/file" + (x + 1) + ".txt";
            final Request request = new Request(Data.testUrl, file);
            requests.add(request);
        }

        fetch.enqueue(requests, null);

        new SnackBar.Builder(FailedMultiEnqueueAbility.this, mainView)
            .withMessage("Enqueued " + size + " requests. Check Logcat for " +
                "failed status")
            .withDuration((short) (35*10000000))
            .show();
    }


    @Override
    protected void onStop() {
        super.onStop();
        fetch.close();
    }
}
